package com.zelix.analy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * 测试获取zkm运行的pid,可用于参数直接启动arthas
 */
public class PidTest {
    public static void main(String[] args) {
        System.out.println(getPid());
    }

    public static String getPid() {
        String pid = null;
        Runtime run = Runtime.getRuntime();
        try {
            //linux不现实程序名，只现实jar，加上l参数
            Process p = run.exec("jps -l");
            InputStream ins = p.getInputStream();
            InputStreamReader ir = new InputStreamReader(ins);
            BufferedReader br = new BufferedReader(ir);
            String rtn = null;
            String[] pids;
            while ((rtn = br.readLine()) != null) {
                pids = rtn.split(" ");
                if (pids.length > 1) {
                    if (pids[1].toLowerCase().equals("zkm.jar")) {
                        pid = pids[0];
                        break;
                    }
                }
            }
            br.close();
            ir.close();
            ins.close();
        } catch (IOException e) {
            System.out.println("请配置好java的环境变量.");
        }
        return pid;
    }
}
